#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTextEdit>//中心部件
#include <QMessageBox> //消息提示框
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QDialog> //模态框
#include <QDebug>
#include <QLabel>
#include <QFont> //字体
#include <QFontDialog> //字体选择框
#include <QStatusBar> //状态栏
#include <QFileDialog> //文件操作框
#include <QFile> //文件操作
#include <QKeySequence> //快捷键

#include <QPushButton>
#include <QDesktopServices>

#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>







MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //标题
    this->setWindowTitle("闲事录");
    this->resize(600,500);


    this->wordSize=ui->textEdit->font().pointSize();

    this->leftStatus=new QLabel("字体大小：");
    this->leftWordStatus=new QLabel("");

    ui->statusBar->addWidget(this->leftStatus);//左边
    ui->statusBar->addWidget(this->leftWordStatus);//左边

    //this->rightStatus=new QLabel("文本字数：");

    this->updateByJson();


    ui->statusBar->addPermanentWidget(this->rightStatus);



    //另存为
     ui->actionSaveAs->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_S));
     connect(ui->actionSaveAs,&QAction::triggered,[this](){
         //打开文本保存框,用户选中文件保存时 得到绝对路径
         //判断用户选择路径不为空
         //得到用户输入内容
         //创建文件对象，使用只读打开，将内容写入到文件中

         this->filePath= QFileDialog::getSaveFileName(this,"另存为","c:/1");

         if(!this->filePath.isEmpty()){
             QString content= ui->textEdit->toPlainText();
             QFile file(this->filePath);
             file.open(QIODevice::WriteOnly);
             file.write(content.toUtf8());
         }
     });


     //保存功能
     ui->actionSave->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
     connect(ui->actionSave,&QAction::triggered,this,&MainWindow::saveFile);






     //新建
     connect(ui->actionNew,&QAction::triggered,[this](){
         // 如果 isSave 为 false时，需要提示保存
         if(this->isSave==false){
             QMessageBox myBox(
                         QMessageBox::Question,
                         "提醒",
                         "你的内容没有保存，请确认是否保存！",
                         QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel
                         );
             myBox.setButtonText(QMessageBox::Yes,"保存");
             myBox.setButtonText(QMessageBox::No,"不保存");
             myBox.button(QMessageBox::Cancel)->setText("取消");

             int choses=myBox.exec();
             if(choses==QMessageBox::Yes)
             {
                 this->saveFile();
                 ui->textEdit->clear();//清空
                 this->isSave=true;
                 this->filePath="";

             }
             else if (choses==QMessageBox::No){
                 ui->textEdit->clear();//清空
                 this->isSave=true;
                 this->filePath="";
             }
         }
     });



     //打开
     connect(ui->actionOpen,&QAction::triggered,[this](){
         this->judgeIsSaved();
         //打开新文件
         this->filePath = QFileDialog::getOpenFileName(this,"打开","c:/","*.txt");
         if(!this->filePath.isEmpty())
         {
            //根据文件路径读取内容
            QFile file(this->filePath);
            file.open(QIODevice::ReadOnly);
            QByteArray buf=file.readAll();
            //将读取的内容设置到textEdit中
            ui->textEdit->setText(QString(buf));

            this->isSave=true;//更新保存状态
         }
     });



    //1.  点击"退出"时，弹出询问框； 继续点击“确定”按钮时退出程序, 点击“取消”, 不关闭程序
    connect(ui->actionExit,&QAction::triggered,[this](){
        this->judgeIsSaved();
        this->close();
    });



    //编辑菜单==================================
    //复制

    ui->actionCopy->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_0));
    connect(ui->actionCopy,&QAction::triggered,ui->textEdit,&QTextEdit::copy);

    //剪切
    ui->actionCut->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_1));
    connect(ui->actionCut,&QAction::triggered,ui->textEdit,&QTextEdit::cut);

    //粘贴
    ui->actionStick->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_2));
    connect(ui->actionStick,&QAction::triggered,ui->textEdit,&QTextEdit::paste);

    //撤销
    connect(ui->actionWithDrawn,&QAction::triggered,ui->textEdit,&QTextEdit::undo);


    //格式菜单==================================
    //自动换行
    connect(ui->actionAutoLineWrap,&QAction::triggered,[this](){
        if(ui->textEdit->lineWrapMode()==QTextEdit::NoWrap){
            ui->textEdit->setLineWrapMode(QTextEdit::WidgetWidth);
            ui->actionAutoLineWrap->setIcon(QIcon(":/images/duihao"));
        }
        else {
            ui->textEdit->setLineWrapMode(QTextEdit::NoWrap);
            ui->actionAutoLineWrap->setIcon(QIcon(""));
        }
    });



        //2. 点击"字体时"，能够弹出字体选择框，最终能够得到用户选择的字体信息。（并能作用到多行文本框上）
        connect(ui->actionFont,&QAction::triggered,[this](){
            bool flag;
            QFont f=QFontDialog::getFont(&flag);
            ui->textEdit->setFont(f);
            this->updateFontSize();
        });








    //3. 点击“状态栏”，有对号，就显示状态栏； 没有对号，就不显示状态栏
    connect(ui->actionStatus,&QAction::triggered,[this](){
        this->statusFlag=!this->statusFlag;
        if(this->statusFlag)
        {
            ui->actionStatus->setIcon(QIcon(":/images/duihao"));
            ui->statusBar->show();
        }
        else
        {
            ui->actionStatus->setIcon(QIcon(""));
            ui->statusBar->hide();
        }
    });



    //4. 点击"缩放"—>"放大" | "缩小"时， 多行文本框中的字体大小会变大、变小
    connect(ui->actionBigger,&QAction::triggered,[this](){
        QFont currFont=ui->textEdit->font();
        currFont.setPointSize(ui->textEdit->font().pointSize()+5);
        ui->textEdit->setFont(currFont);
        this->updateFontSize();
    });
    connect(ui->actionSmaller,&QAction::triggered,[this](){
        QFont currFont=ui->textEdit->font();
        currFont.setPointSize(ui->textEdit->font().pointSize()-5);
        ui->textEdit->setFont(currFont);
        this->updateFontSize();
    });


    //5. 点击“关于我们”， 弹出一个模态框，在模态框中显示软件说明信息
    connect(ui->actionAboutUs,&QAction::triggered,[](){
        QDialog aboutUsDia;
        aboutUsDia.setWindowTitle("闲事录");
        aboutUsDia.resize(300,200);
        aboutUsDia.setStyleSheet("background-color:palegreen");


        //设置内容
        QLabel *l1=new QLabel("闲事录团队",&aboutUsDia);
        l1->move(180,80);
        l1->setFont(QFont("楷体",14));
        l1->setStyleSheet("color:purple");

        QLabel *l2=new QLabel("Tel:17669676769",&aboutUsDia);
        l2->move(150,170);
        l2->setFont(QFont("楷体",14));
        l2->setStyleSheet("color:red");

        //设置图片
        QLabel *l3=new QLabel(&aboutUsDia);
        l3->resize(160,160);
        l3->setPixmap(QPixmap(":/images/logo"));
        l3->setScaledContents(true);

        QPushButton *p1=new QPushButton("关闭",&aboutUsDia);
        p1->move(50,170);
        p1->setStyleSheet("background-color:#e5e5e5");
        connect(p1,&QPushButton::clicked,&aboutUsDia,&QDialog::close);
        aboutUsDia.exec();
    });


    //帮助菜单==================================
    //打开浏览器
    connect(ui->actionHelpDoc,&QAction::triggered,[](){
        QDesktopServices::openUrl(QUrl("http://t.csdnimg.cn/v189s"));
    });




}


MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_textEdit_textChanged()
{
    this->isSave=false;
}


//保存文件
void MainWindow::saveFile(){
    if(this->filePath.isEmpty()){
        //若未保存过 准备一个filePath ,保存过 无需此步骤
        this->filePath = QFileDialog::getSaveFileName(this,"保存","c:/1","*.txt");
        if(this->filePath.isEmpty()){
            return;
        }
    }
    QString content=ui->textEdit->toPlainText();
    QFile file(this->filePath);
    file.open(QIODevice::WriteOnly);
    file.write(content.toUtf8());
    this->isSave = true;//更新保存状态
}


//判断文件是否已经保存过
void MainWindow::judgeIsSaved()
{
    if(this->isSave==false)
    {
        QMessageBox myBox(
                    QMessageBox::Question,
                    "提醒",
                    "你的内容没有保存，请确认是否保存！",
                    QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel
                    );
        myBox.setButtonText(QMessageBox::Yes,"保存");
        myBox.setButtonText(QMessageBox::No,"不保存");
        myBox.button(QMessageBox::Cancel)->setText("取消");

        int choses=myBox.exec();
        if(choses==QMessageBox::Cancel)
        {
            return ;
        }

        if (choses==QMessageBox::Yes){
            //执行保存
            this->saveFile();
        }
        this->isSave=true;//更新保存状
    }
}


//更新字体大小 并记录在json文件中
void MainWindow::updateFontSize()
{
    this->wordSize=ui->textEdit->font().pointSize();
    this->wordItalic =ui->textEdit->font().italic();
    this->wordWeight = ui->textEdit->font().weight();
    this->wordFamily= ui->textEdit->font().family();
    this->leftWordStatus->setNum(this->wordSize);
    //创建json对象
    QJsonObject jsonObj;
    QJsonArray arrSql;//创建空数组
    //向数组中添加对象
    QJsonObject obj;//创建空对象
    obj.insert("size",this->wordSize);
    obj.insert("italic",this->wordItalic);
    obj.insert("weight",this->wordWeight);
    obj.insert("family",this->wordFamily);

    arrSql.append(obj);
    //把arr 添加到json对象中
    jsonObj.insert("wordInfo",arrSql);

    //将数组 转为 json文档
    QJsonDocument jsonDoc(jsonObj);

    //将json文档  转为json字符串
    QByteArray jsonStr= jsonDoc.toJson(QJsonDocument::Indented);
    //将json字符串写入文件中
    QString currentPath = QDir::currentPath();
    qDebug()<<currentPath;
//    QFile file("c:/0/word.json");
    QFile file(currentPath+"/word.json");
    file.open(QIODevice::WriteOnly);
    file.write(jsonStr);
    file.close();
}


//初始化更新字体
void MainWindow::updateByJson()
{

    //通过file  读取json文件  获取json字符串
    QString currentPath = QDir::currentPath();
    qDebug()<<currentPath;
//    QFile file("c:/0/word.json");

    QFile file(currentPath+"/word.json");
//     file.open(QIODevice::ReadOnly);
    if (file.open(QIODevice::ReadOnly))
    {
        QByteArray jsonStr =file.readAll();

        //将json字符串  转为json文档
        QJsonDocument jsonDoc= QJsonDocument::fromJson(jsonStr);

        //将json文档   转为  json对象
        QJsonObject jsonObj= jsonDoc.object();

        //操作数组中对象
        QJsonArray ary = jsonObj.value("wordInfo").toArray();

        QJsonObject wordObj=ary.at(0).toObject();

        this->wordFamily = wordObj.value("family").toString();
        this->wordSize = wordObj.value("size").toInt();
        this->wordWeight = wordObj.value("bold").toInt();
        this->wordItalic = wordObj.value("italic").toBool();
    }

    QFont font;
    font.setBold(this->wordWeight);
    font.setFamily(this->wordFamily);
    font.setItalic(this->wordItalic);
    font.setPointSize(this->wordSize);
    ui->textEdit->setFont(font);


    this->leftWordStatus->setNum(this->wordSize);

}
